import { t } from 'i18next'
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from 'react'
import { Search, useSelection } from '@kedacom/react-next'
import { StyledPollModal } from './style'
import { Avatar } from '@/pages/manager/components'
import { Mt } from '@/api/manager/mt'
import { useMccStore } from '@/pages/manager/store'
import shallow from 'zustand/shallow'
import { getItemByMtKey } from '../../main/table/all/utils'
import { useTableAllStore } from '../../main/table/all/store'
import { useTableOftenStore } from '../../main/table/often/store'
import { xor } from 'lodash-es'
import { useGlobalStore } from '@/store/global'

export interface PollModalProps {
	data: Mt[]
}
export type PollModalRef = {
	reset: () => void
	getValue: () => Mt[]
}
const PollModal = forwardRef((props: PollModalProps, ref: React.Ref<PollModalRef>) => {
	const { data } = props
	const { superMtNum } = useMccStore(
		(state) => ({
			superMtNum: state.mccInfo.superMtNum,
		}),
		shallow
	)
	const [batchMembers, setBatchMembers] = useState<Mt[]>([])
	const [oftenMembers, setOftenMembers] = useState<Mt[]>([])
	const tableAll = useTableAllStore((state) => state.tree)
	const tableOften = useTableOftenStore((state) => state.list)
	useEffect(() => {
		if (tableAll) {
			const _tree = getItemByMtKey(tableAll, '0.0.0.0_0')
			if (_tree) {
				const batch = (_tree.children.filter((item) => item.mcc.isMt).map((_value) => _value.mcc) as Mt[]) || []
				setBatchMembers(batch)
			}
		}
	}, [tableAll])
	useEffect(() => {
		if (tableOften) {
			setOftenMembers(tableOften.filter((x) => x.mcc.confLevel === 2).map((x) => x.mcc))
		}
	}, [tableOften])
	const [isOften, setIsOften] = useState(false)
	const [searchValue, setSearchValue] = useState('')
	const showData = useMemo(() => {
		let newList = isOften ? oftenMembers : batchMembers
		if (searchValue) newList = newList.filter((item: any) => item.name.indexOf(searchValue) !== -1)
		return newList
	}, [batchMembers, oftenMembers, isOften, searchValue])
	//选择框中全部数据
	const selectList = useMemo(() => {
		let arr = [...batchMembers]
		data.forEach((item) => {
			//插入右侧列表选中但非左侧列表的数据
			let flag = batchMembers.find((j) => j.mtKey === item.mtKey) /**item 存在于左侧列表 */
			if (!flag) arr.push(item) /**被选中的数据应该有这个终端但是全部终端没有当前数据*/
		})
		return arr
	}, [batchMembers])
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	const {
		selectedItems,
		isSelected,
		cancelSelect,
		isChecked,
		isSelectedItemChecked,
		selectedItemChecked,
		itemChecked,
		itemSelect,
		clearChecked,
		clearAllSelected,
		setCheckedToSelected,
		cancelCheckedFromSelected,
		selectAll,
		setSelectedItems,
		sortSelectedItems,
	} = useSelection(selectList, 'mtKey')
	useEffect(() => {
		let arr: Mt[] = []
		data.forEach((i) => {
			let item = selectList.find((j) => j.mtKey === i.mtKey)
			if (item) arr.push(item)
		})
		setSelectedItems(arr)
	}, [])
	useEffect(() => {
		setSelectedItems((prev) => {
			let arr: Mt[] = []
			prev.forEach((i) => {
				let item = selectList.find((j) => j.mtKey === i.mtKey)
				if (item) arr.push(item)
			})
			return arr
		})
	}, [selectList])
	const reset = () => {
		setSelectedItems([])
		setIsOften(false)
		setSearchValue('')
	}
	useImperativeHandle(ref, () => ({
		reset() {
			reset()
		},
		getValue() {
			return selectedItems
		},
	}))
	return (
		<StyledPollModal className="simple-poll-modal__i18n" superMtNum={superMtNum || !SWITCH.showOftenMt ? 1 : 0}>
			<div className="transfer-wrap">
				<div className="left-list">
					{superMtNum === 0 && !!SWITCH.showOftenMt && (
						<div className="tab">
							<span
								className={`${!isOften ? 'selected' : ''}`}
								onClick={() => {
									setIsOften(false)
								}}
							>
								{t('全部终端')}
							</span>
							<span
								className={`${isOften ? 'selected' : ''}`}
								onClick={() => {
									setIsOften(true)
								}}
							>
								{t('常用终端')}
							</span>
						</div>
					)}
					<div className="content">
						<div className="search-wrap">
							<Search
								iconAlign="left"
								placeholder={t('搜索')}
								value={searchValue}
								onChange={(e, val) => {
									setSearchValue(val)
								}}
								onClear={() => setSearchValue('')}
								clearable
							/>
						</div>
						{showData.map((item, index) => (
							<div
								className={`list-item ${isSelected(item) ? 'selected' : ''} ${
									isChecked(item) ? 'checked' : ''
								} `}
								onClick={(e) => {
									itemChecked(e, item, index, false)
								}}
								onDoubleClick={() => {
									itemSelect(item)
									clearChecked()
								}}
								key={item.mtKey}
							>
								<span className="icon-wrap">
									<span className="icon" />
								</span>
								<Avatar value={item as any} />
								<span className="name">{item.name}</span>
							</div>
						))}
					</div>
				</div>
				<div className="transfer-operate">
					<span className="btn all-right" onClick={() => selectAll()} />
					<span className="btn right" onClick={() => setCheckedToSelected()} />
					<span className="btn left" onClick={() => cancelCheckedFromSelected()} />
					<span className="btn all-left" onClick={() => clearAllSelected()} />
				</div>
				<div className="right-list">
					<div className="title">{t('已选{{num}}位', { num: selectedItems.length })}</div>
					<div className="content">
						{selectedItems.map((item, index) => (
							<div
								className={`list-item ${isSelectedItemChecked(item) ? 'checked' : ''}`}
								onClick={(e) => {
									selectedItemChecked(e, item, index, false)
								}}
								onDoubleClick={() => {
									cancelSelect(item)
									clearChecked()
								}}
								key={item.mtKey}
							>
								<span
									className="icon-wrap"
									onClick={(e) => {
										e.stopPropagation()
										selectedItemChecked(e, item, index, true)
									}}
								>
									<span className="icon" />
								</span>
								<Avatar value={item as any} />
								<span className="name">{item.name}</span>
							</div>
						))}
					</div>
				</div>
				<div className="right-operate">
					<span className="btn top" onClick={() => sortSelectedItems('top')} />
					<span className="btn up" onClick={() => sortSelectedItems('up')} />
					<span className="btn down" onClick={() => sortSelectedItems('down')} />
					<span className="btn bottom" onClick={() => sortSelectedItems('bottom')} />
				</div>
			</div>
		</StyledPollModal>
	)
})
export default PollModal
